package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品和对应口味
     *
     * @param dishDTO
     */
    //因为同时操作多表，所以加入事务管理，同时提交或失败
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        //向菜品表插入一条数据
        //去除dishDTO中口味字段
        Dish dish = new Dish();
        //通过对象属性拷贝赋值
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);

        //获取新插入的菜品的id  在xml设置了获取新增的主键值，并赋值给实体类的id属性
        Long dishId = dish.getId();

        //向口味表插入多条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //遍历每一项，将dishId赋值给每一项，指定设置的口味是属于哪个菜品的
            flavors.forEach(item -> {
                item.setDishId(dishId);
            });
            //批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //pagehelper查询
        //通过菜品表和分类表多表查询,根据菜品表的分类id在category中查询分类名称
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        long total = page.getTotal();  //总条数
        List<DishVO> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     */
    //同时操作删除多表，使用事务管理，同时提交或失败
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //业务要求：
        //1.起售中的菜品不能删除
        //2.被套餐关联的菜品不能删除
        //3.删除菜品后，关联的口味数据也需要删除掉

        //判断当前菜品是否起售
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断当前菜品是否被套餐关联，根据菜品id查询套餐id
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的数据
        dishMapper.deleteBatch(ids);

        //删除关联的口味数据
        dishFlavorMapper.deleteByDishIds(ids);
    }

    public DishVO getByIdWithFlavor(Long id) {
        //1.从dish表中查询菜品数据
        Dish dish = dishMapper.getById(id);

        //2.从dish_flavor表中查询菜品对应口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //3.封装到DishVO中并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 根据id修改菜品信息和对应口味信息
     *
     * @param dishDTO
     */

    //修改多表，加入事务注解管理
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改dish表中相关信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //修改对应口味的信息， 先删除对应的所有口味，再添加口味
        Long dishId = dishDTO.getId();
        List<Long> listid = new ArrayList<>();
        listid.add(dishId);
        dishFlavorMapper.deleteByDishIds(listid);
        //重新插入口味数据
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (dishFlavors != null && dishFlavors.size() > 0) {
            //遍历每一项，将dishId赋值给每一项，指定设置的口味是属于哪个菜品的
            dishFlavors.forEach(item -> {
                item.setDishId(dishId);
            });
            //批量插入
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }

    public void tabStatus(Integer status, Long id) {
        //TODO 菜品有关联的并且起售的套餐时，菜品不能停售


        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     */
    public List<Dish> getByCategoryId(Long categoryId) {
        //TODO 修改为传参dish对象，set状态属性，让其只查询到状态为起售的菜品
        return dishMapper.getByCategoryId(categoryId);
    }

    /**
     * 根据条件查询菜和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        //根据dish参数中包含  分类id，状态  查询
        //先通过分类id查询菜品数据
        List<Dish> dishList = dishMapper.getByCategoryId(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        //遍历dishList中每一项，通过菜品id查询对应口味，将菜品和口味封装到dishVO中，将VO添加到dishVOList中
        dishList.forEach(d -> {
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            //封装进VO
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            dishVO.setFlavors(flavors);
            //将VO添加到dishVOList中
            dishVOList.add(dishVO);
        });

        return dishVOList;
    }
}
